package loengud.w13;

import java.util.ArrayList;
import java.util.List;

public class Ttt {
	
	/**
	 * 012
	 * 345
	 * 678
	 */
	int[] board = {
			0, 0, 0,
			0, 0, 0,
			0, 0, 0
	};
	
	public static final int EMPTY = 0;
	public static final int PLAYER1 = 1;
	public static final int INFINITY = Integer.MAX_VALUE;
	
	
	int[][] wins = {
			{0, 1, 2},
			{3, 4, 5},
			{6, 7, 8},
			
			{0, 3, 6},
			{1, 4, 7},
			{2, 5, 8},
			
			{0, 4, 8},
			{2, 4, 6}
	};

	public static void main(String[] args) {
		Ttt t = new Ttt();
		t.run();

	}

	public void run() {
		
	}
	
	public boolean checkWin(int[] b) {
		//for (int i = 0; i < wins.length; i++) {
			
		//}
		for (int[] w : wins) {
			if (b[w[0]] != EMPTY &&
					b[w[0]] == b[w[1]] &&
					b[w[1]] == b[w[2]]) {
				return true;
			}
		}
		return false;
	}
	
	public List<Integer> getMoves(int[] b) {
		List<Integer> moves = new ArrayList<Integer>();
		for (int i = 0; i < board.length; i++) {
			if (b[i] == EMPTY) moves.add(Integer.valueOf(i));
		}
		return moves;
	}
	
	public int minimax(int player, int[] board, int depth) {
		// evalution
		if (checkWin(board)) {
			// winner = previous player
			if (player == PLAYER1) {
				return -1000;
			} else {
				// opponent's move, I won
				return 1000;
			}
		}
		if (depth <= 0) return 0; // evaluation
		int best = INFINITY;
		if (player == PLAYER1) best = -INFINITY;
		
		List<Integer> moves = getMoves(board);
		for (int m : moves) {
			board[m] = player;
			// go deep
			int val = minimax(3 - player, board, depth - 1);
			board[m] = EMPTY;
			
			if (player == PLAYER1) {
				// MAX
				best = Math.max(best, val);
				// if (val > bestVal) best = val;
			} else {
				best = Math.min(best, val);
			}
		}
		return best;
	}
}
